package cn.zcscloud.mall.controller;

import cn.zcscloud.mall.common.PageRequest;
import cn.zcscloud.mall.common.R;
import cn.zcscloud.mall.dto.OmsOrderDto;
import cn.zcscloud.mall.mbg.model.OmsOrder;
import cn.zcscloud.mall.mbg.model.OmsOrderItem;
import cn.zcscloud.mall.mbg.model.OmsOrderOperateHistory;
import cn.zcscloud.mall.mbg.model.OmsOrderReturnApply;
import cn.zcscloud.mall.service.OmsOrderItemService;
import cn.zcscloud.mall.service.OmsOrderOperateHistoryService;
import cn.zcscloud.mall.service.OmsOrderReturnApplyService;
import cn.zcscloud.mall.service.OmsOrderService;
import cn.zcscloud.mall.vo.MoneyInfoVo;
import cn.zcscloud.mall.vo.OrderVo;
import cn.zcscloud.mall.vo.ReceiverVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OmsOrderController {

    @Autowired
    private OmsOrderService omsOrderService;

    @Autowired
    private OmsOrderReturnApplyService orderReturnApplyService;

    @Autowired
    private OmsOrderOperateHistoryService omsOrderOperateHistoryService;

    @Autowired
    private OmsOrderItemService omsOrderItemService;

    /**
     * 获取订单列表
     *
     * @param orderVo
     * @return
     */
    @GetMapping("/list")
    public R list(OrderVo orderVo) {
        LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orderVo.getOrderSn() != null, OmsOrder::getOrderSn, orderVo.getOrderSn())
                .eq(orderVo.getReceiverKeyword() != null, OmsOrder::getReceiverPhone, orderVo.getReceiverKeyword())
                .eq(orderVo.getOrderType() != null, OmsOrder::getOrderType, orderVo.getOrderType())
                .eq(orderVo.getSourceType() != null, OmsOrder::getSourceType, orderVo.getSourceType())
                .eq(orderVo.getStatus() != null, OmsOrder::getStatus, orderVo.getStatus())
                .like(orderVo.getCreateTime() != null, OmsOrder::getCreateTime, orderVo.getCreateTime());

        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(Math.toIntExact(orderVo.getPageNum()));
        pageRequest.setPageSize(Math.toIntExact(orderVo.getPageSize()));
        Page<OmsOrder> orderPage = new Page<>(orderVo.getPageNum(), orderVo.getPageSize());
        Page<OmsOrder> page = omsOrderService.page(orderPage, queryWrapper);
        pageRequest.setList(page.getRecords());
        pageRequest.setTotal(Math.toIntExact(page.getTotal()));
        return R.success(pageRequest);
    }

    //获取订单详情
    @GetMapping("/{id}")
    public R getOrderInfo(@PathVariable("id") Long id) {
        //根据id查找订单
        LambdaQueryWrapper<OmsOrder> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OmsOrder::getId, id);
        OmsOrder omsOrder = omsOrderService.getOne(queryWrapper1);
        OmsOrderDto omsOrderDto = new OmsOrderDto();
        BeanUtils.copyProperties(omsOrder, omsOrderDto);
        //查找操作记录
        LambdaQueryWrapper<OmsOrderOperateHistory> queryWrapper2 = new LambdaQueryWrapper();
        queryWrapper2.eq(OmsOrderOperateHistory::getOrderId, id);
        List<OmsOrderOperateHistory> historyList = omsOrderOperateHistoryService.list(queryWrapper2);

        LambdaQueryWrapper<OmsOrderItem> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(OmsOrderItem::getOrderId, id);
        List<OmsOrderItem> itemList = omsOrderItemService.list(queryWrapper3);

        omsOrderDto.setHistoryList(historyList);
        omsOrderDto.setOrderItemList(itemList);

        return R.success(omsOrderDto);
    }

    //订单发货
    @PostMapping("/update/delivery")
    public R delivery(@RequestBody List<Map> list) {
        System.out.println(list);
        for (Map map : list) {
            LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(map.get("orderId") != null, OmsOrder::getId, map.get("orderId"));
            OmsOrder omsOrder = omsOrderService.getOne(queryWrapper);
            omsOrder.setDeliverySn((String) map.get("deliverySn"));
            omsOrder.setDeliveryCompany((String) map.get("deliveryCompany"));
            omsOrder.setStatus(2);
            omsOrderService.updateById(omsOrder);
        }
        return R.success("发货成功!", null);
    }

    //删除订单
    @PostMapping("/delete")
    public R deleteOrder(@RequestParam List<Long> ids) {
        List<OmsOrder> list = omsOrderService.listByIds(ids);
        for (OmsOrder order : list) {
            if (order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 2) {
                return R.error("当前订单未完成,无法删除.", null);
            }
        }

        LambdaQueryWrapper<OmsOrderReturnApply> queryWrapper = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            queryWrapper.eq(OmsOrderReturnApply::getOrderId, id);
            List<OmsOrderReturnApply> applies = orderReturnApplyService.list(queryWrapper);
            for (OmsOrderReturnApply apply : applies) {
                if (apply.getStatus() == 1|| apply.getStatus() == 0) {
                    return R.error("订单处于退货申请状态,无法删除", null);
                }
            }
        }

        omsOrderService.removeByIds(ids);
        return R.success("删除成功", null);
    }

    //备注订单
    @PostMapping("/update/note")
    public R note(Integer id, String note, Integer status) {
        //System.out.println(id + note+status);
        OmsOrder omsOrder = omsOrderService.getById(id);
        omsOrder.setNote(note);
        omsOrderService.updateById(omsOrder);
        return R.success("备注成功", null);
    }

    //修改收货人信息
    @PostMapping("/update/receiverInfo")
    public R receiverInfo(@RequestBody ReceiverVo receiverVo) {
        OmsOrder omsOrder = omsOrderService.getById(receiverVo.getOrderId());
        BeanUtils.copyProperties(receiverVo, omsOrder);
        omsOrderService.updateById(omsOrder);
        return R.success("修改成功", null);
    }

    //批量关闭订单
    @PostMapping("/update/close")
    public R close(@RequestParam List<Long> ids, String note) {
        LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OmsOrder::getId, ids);
        List<OmsOrder> list = omsOrderService.list(queryWrapper);
        for (OmsOrder omsOrder : list) {
            if (omsOrder.getStatus() != 0) {
                return R.error("当前无法关闭", null);
            }
        }

        for (OmsOrder omsOrder : list) {
            omsOrder.setStatus(4);
            omsOrder.setNote(note);
            omsOrderService.updateById(omsOrder);
        }
        return R.success("关闭成功", null);
    }


    //修改订单费用信息
    @PostMapping("/update/moneyInfo")
    public R moneyInfo(@RequestBody MoneyInfoVo moneyInfoVo) {
        LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(moneyInfoVo.getOrderId() != null, OmsOrder::getId, moneyInfoVo.getOrderId());
        OmsOrder omsOrder = omsOrderService.getOne(queryWrapper);
        if (moneyInfoVo.getStatus() != 0) {
            return R.error("无法更改", null);
        }
        omsOrder.setFreightAmount(moneyInfoVo.getFreightAmount());
        omsOrder.setDiscountAmount(moneyInfoVo.getDiscountAmount());
        omsOrderService.updateById(omsOrder);
        return R.success("修改成功!", null);
    }
}
